package com.axend.aerosense.dev.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.common.base.IHostLayout;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.connect.DeviceConnectManager;
import com.axend.aerosense.common.connect.impl.IScanResult;
import com.axend.aerosense.common.connect.impl.IScanCallback;
import com.axend.aerosense.common.connect.bean.WifiScanResultBean;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.activity.DevBaseWifiActivity;
import com.axend.aerosense.dev.databinding.DevFragmentFindHotBinding;
import com.axend.aerosense.dev.viewmodel.ConnectWifiViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ChenHongWei
 * @date :2021/1/12 17:21
 */

public class DevConnectWifiFragment
        extends MvvmBaseFragment<DevFragmentFindHotBinding, ConnectWifiViewModel>
        implements IScanCallback {

    public static final String DEVICE_SSID = "DEVICE_SSID";
    private static final String WIFI_NAME_PREFIX = "AS_";

    private List<Map<String, Object>> listMap;
    private Activity mActivity;
    private boolean isOnResume = true;
    private DeviceConnectManager connectManager;

    public static DevConnectWifiFragment getInstance(){
        DevConnectWifiFragment fragment = new DevConnectWifiFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView(){
        connectManager = ((DevBaseWifiActivity) getActivity()).getDeviceConnectManager();

        viewModel.getIsConnectNow().setValue(true);
        //viewDataBinding.devSpinner.setDropDownVerticalOffset(DisplayUtils.dip2px(45));
        viewDataBinding.devNext.setOnClickListener(v -> {
            String ssid = listMap.get(viewDataBinding.devSpinner.getSelectedItemPosition())
                    .get("name")
                    .toString();
            //连接wifi
            if (ssid.startsWith(WIFI_NAME_PREFIX)){
                viewModel.getIsConnectNow().setValue(false);
                LiveDatabus.getInstance()
                        .with(Gobal.EVENT_KEY.CONNECT_BROKEN, Boolean.class)
                        .postValue(false);
                toNextPage(ssid);
            }else {
                ToastUtils.showShort(R.string.dev_please_connect_as_wifi_tips);
            }
        });

        //重新扫描
        viewDataBinding.devReScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DevBaseWifiActivity devBaseWifiActivity = getWifiActivity();
                try{
                    if (null != devBaseWifiActivity && devBaseWifiActivity.isEnableWifi()){
                        viewModel.getIsShowWaitView().setValue(true);
                        connectManager.reScanWifi();
                    }else {
                        viewModel.getIsShowWaitView().setValue(false);
                        viewModel.getIsConnectNow().setValue(true);
                        ToastUtils.showShort(R.string.dev_scan_wifi_failed);
                    }
                }catch (Exception e){

                }
            }
        });

        //连接中断事件
        LiveDatabus.getInstance()
                .with(Gobal.EVENT_KEY.CONNECT_BROKEN, Boolean.class)
                .observe(getViewLifecycleOwner(), b -> {
                    if (b){
                        showConnectFailTips();
                    }
                });
    }

    //获取wifi列表
    private void getWifiList(){
        viewModel.getIsShowWaitView().setValue(true);
        //此处延时操作，解决刚打开wifi搜索wifi失败问题
        new Handler().postDelayed(() -> {
            try{
                DevBaseWifiActivity devBaseWifiActivity = getWifiActivity();
                if (null != devBaseWifiActivity && devBaseWifiActivity.isEnableWifi()){
                    connectManager.scanWifi();
                }else {
                    viewModel.getIsShowWaitView().setValue(false);
                    viewModel.getIsConnectNow().setValue(true);
                    ToastUtils.showShort(R.string.dev_scan_wifi_failed);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }, 2000);
    }

    private DevBaseWifiActivity getWifiActivity(){
        FragmentActivity activity = getActivity();
        if (activity instanceof DevBaseWifiActivity) {
            return (DevBaseWifiActivity) activity;
        }
        return null;
    }

    //去下一个页面
    private void toNextPage(String ssid){
        Bundle bundle = getArguments();
        bundle.putString(DEVICE_SSID, ssid);
        Fragment fragment = DevFamilyWifiFragment.getInstance();
        fragment.setArguments(bundle);
        int contentId = ((IHostLayout)getActivity()).getContentId();
        viewModel.getIsConnectNow().setValue(true);
        FragmentUtil.add(getActivity(), contentId, fragment, this, true);
    }

    private void setDataList(List<IScanResult> dataList){
        if (dataList.size() == 0 || dataList.isEmpty() || dataList == null){
            return;
        }
        listMap = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++){
            Map<String, Object> items = new HashMap<>();
            String wifiName = dataList.get(i).getName();
            if (wifiName.startsWith(WIFI_NAME_PREFIX)){
                items.put("name", wifiName);
                listMap.add(items);
            }

        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(mActivity,
                listMap,
                R.layout.dev_layout_spinner_item,
                new String[]{"name"},
                new int[]{R.id.dev_wifi_name}
        );
        viewDataBinding.devSpinner.setAdapter(simpleAdapter);
    }

    /**
     * 设置设备中途断开连接提示
     */
    private void showConnectFailTips(){
        String country = getResources().getConfiguration().locale.getLanguage();
        LogUtils.d("系统语言：" + country);
        int start;
        int end;
        //英文版本
        start = 91;
        end = 124;
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(getString(R.string.dev_hot_connect_fail_tips));

        //设置部分文字可点击
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //跳转到wifi设置界面
                startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
            }
        };
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#3578FC"));
        try{
            stringBuilder.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            stringBuilder.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }catch (Exception e){

        }

        viewDataBinding.devHotTips.setText(stringBuilder);
        viewDataBinding.devHotTips.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * wifi扫描结果回调
     * @param list
     */
    @Override
    public void scanResult(List<IScanResult> list) {
        //wifi扫描结果回调
        LogUtils.d("wifiList:" + list);

        if (null == list || list.isEmpty()) {
            return;
        }

        if (list.get(0) instanceof WifiScanResultBean) {
            setDataList(list);
            //停止wifi扫描
            viewModel.getIsShowWaitView().setValue(false);
            viewModel.getIsConnectNow().setValue(true);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isOnResume){
            ((ITitle)getActivity()).setTitle(getString(R.string.dev_connect_new_hot_dev));
            getWifiList();
            isOnResume = false;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity=activity;
    }

//    /**
//     * 设备连接成功或失败回调
//     * @param isSuccess
//     */
//    @Override
//    public void isConnectSuccess(boolean isSuccess) {
//        ((IWaitDialog) getActivity()).hideWaitDialog();
//        if (isSuccess){
//            viewModel.getIsConnectNow().setValue(false);
//            toNextPage();
//        }else {
//            showConnectFailTips();
//            viewModel.getIsConnectNow().setValue(true);
//            ToastUtils.shortToast(R.string.dev_device_wifi_unconnected);
//        }
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_find_hot;
    }

    @Override
    public int getBindingVariable() {
        return BR.viewmodel;
    }

    @Override
    protected ConnectWifiViewModel getViewModel() {
        return new ViewModelProvider(this).get(ConnectWifiViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {

    }
}
